<template>
  <div class="sensor-detail-modal" v-if="visible" @click.self="closeModal">
    <div class="modal-content">
      <div class="modal-header">
        <h2>{{ title }} - 详细数据</h2>
        <button class="close-btn" @click="closeModal">×</button>
      </div>

      <div class="chart-container">
        <div class="chart-section">
          <h3>24小时数据趋势</h3>
          <div class="chart-wrapper">
            <div class="chart-placeholder">
              <div class="chart-title">24小时 {{ title }} 数据</div>
              <div class="chart-data">
                <div v-for="(item, index) in hourlyData" :key="index" class="data-bar">
                  <div class="bar" :style="{ height: (item.value / maxValue) * 100 + '%' }"></div>
                  <div class="time">{{ item.time }}</div>
                  <div class="value">{{ item.value }}{{ unit }}</div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div class="chart-section">
          <h3>一周数据趋势</h3>
          <div class="chart-wrapper">
            <div class="chart-placeholder">
              <div class="chart-title">一周 {{ title }} 数据</div>
              <div class="chart-data weekly">
                <div v-for="(item, index) in weeklyData" :key="index" class="data-bar">
                  <div class="bar" :style="{ height: (item.value / maxWeeklyValue) * 100 + '%' }"></div>
                  <div class="time">{{ item.day }}</div>
                  <div class="value">{{ item.value }}{{ unit }}</div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 统计数据部分 -->
        <div class="stats-section">
          <h3>数据统计</h3>
          <div class="stats-grid">
            <div class="stat-item">
              <div class="stat-icon">📊</div>
              <div class="stat-content">
                <div class="stat-label">当前值</div>
                <div class="stat-value">{{ currentValue }}{{ unit }}</div>
              </div>
            </div>
            <div class="stat-item">
              <div class="stat-icon">🔺</div>
              <div class="stat-content">
                <div class="stat-label">今日最高</div>
                <div class="stat-value">{{ stats.todayMax }}{{ unit }}</div>
              </div>
            </div>
            <div class="stat-item">
              <div class="stat-icon">🔻</div>
              <div class="stat-content">
                <div class="stat-label">今日最低</div>
                <div class="stat-value">{{ stats.todayMin }}{{ unit }}</div>
              </div>
            </div>
            <div class="stat-item">
              <div class="stat-icon">⌀</div>
              <div class="stat-content">
                <div class="stat-label">今日平均</div>
                <div class="stat-value">{{ stats.todayAvg }}{{ unit }}</div>
              </div>
            </div>
            <div class="stat-item">
              <div class="stat-icon">📈</div>
              <div class="stat-content">
                <div class="stat-label">周最高</div>
                <div class="stat-value">{{ stats.weeklyMax }}{{ unit }}</div>
              </div>
            </div>
            <div class="stat-item">
              <div class="stat-icon">📉</div>
              <div class="stat-content">
                <div class="stat-label">周最低</div>
                <div class="stat-value">{{ stats.weeklyMin }}{{ unit }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, watch, onMounted } from 'vue';

export default {
  name: 'SensorDetailChart',
  props: {
    visible: Boolean,
    sensorType: String,
    currentValue: Number
  },
  emits: ['close'],
  setup(props, { emit }) {
    const title = computed(() => {
      const titles = {
        'light': '光照强度',
        'co2': '二氧化碳浓度',
        'ph': '土壤PH值'
      };
      return titles[props.sensorType] || props.sensorType;
    });

    const unit = computed(() => {
      const units = {
        'light': ' MG/KG',
        'co2': ' MG/KG',
        'ph': ''
      };
      return units[props.sensorType] || '';
    });

    // 模拟24小时数据
    const hourlyData = ref([]);
    // 模拟一周数据
    const weeklyData = ref([]);
    // 统计数据
    const stats = ref({
      todayMax: 0,
      todayMin: 0,
      todayAvg: 0,
      weeklyMax: 0,
      weeklyMin: 0
    });

    const maxValue = computed(() => {
      const max = Math.max(...hourlyData.value.map(item => item.value), 1);
      return max === 0 ? 1 : max;
    });

    const maxWeeklyValue = computed(() => {
      const max = Math.max(...weeklyData.value.map(item => item.value), 1);
      return max === 0 ? 1 : max;
    });

    const generateMockData = () => {
      console.log('Generating mock data for:', props.sensorType, 'currentValue:', props.currentValue);

      // 根据传感器类型设置合理的基准值和波动范围
      const baseConfig = {
        'light': {
          base: props.currentValue || 800,
          dayVariation: 300,
          nightVariation: 100,
          min: 200,
          max: 1200
        },
        'co2': {
          base: props.currentValue || 400,
          dayVariation: 150,
          nightVariation: 80,
          min: 300,
          max: 800
        },
        'ph': {
          base: props.currentValue || 6.5,
          dayVariation: 0.8,
          nightVariation: 0.4,
          min: 5.5,
          max: 7.5
        }
      };

      const config = baseConfig[props.sensorType] || {
        base: props.currentValue || 50,
        dayVariation: 20,
        nightVariation: 10,
        min: 0,
        max: 100
      };

      // 生成24小时数据 - 模拟真实的日间波动
      const hourly = [];
      for (let i = 0; i < 24; i++) {
        // 更真实的日间波动模型
        let timeFactor;
        if (i >= 6 && i <= 18) {
          // 白天：6-18点，中午12点达到峰值
          const hourFromNoon = Math.abs(i - 12);
          timeFactor = 1 - (hourFromNoon / 12) * 0.4; // 中午最高，早晚较低
        } else {
          // 夜晚：较低的基础值
          timeFactor = 0.6;
        }

        // 添加随机波动
        const isDaytime = i >= 6 && i <= 18;
        const randomVariation = (Math.random() - 0.5) * (isDaytime ? config.dayVariation : config.nightVariation);

        let value = config.base * timeFactor + randomVariation;

        // 限制在合理范围内
        value = Math.max(config.min, Math.min(config.max, value));

        // 根据类型格式化数值
        if (props.sensorType === 'ph') {
          value = Number(value.toFixed(1));
        } else {
          value = Math.round(value);
        }

        hourly.push({
          time: `${i.toString().padStart(2, '0')}:00`,
          value: value
        });
      }
      hourlyData.value = hourly;

      // 生成一周数据 - 模拟周变化
      const days = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
      const weekly = [];

      // 设置一周的基础趋势（例如：周中较高，周末较低）
      const weeklyTrend = [0.9, 1.0, 1.1, 1.05, 1.0, 0.95, 0.9]; // 周三最高

      for (let i = 0; i < 7; i++) {
        const trendFactor = weeklyTrend[i];
        const weeklyVariation = (Math.random() - 0.5) * config.dayVariation * 0.5;
        let value = config.base * trendFactor + weeklyVariation;

        // 限制在合理范围内
        value = Math.max(config.min, Math.min(config.max, value));

        // 根据类型格式化数值
        if (props.sensorType === 'ph') {
          value = Number(value.toFixed(1));
        } else {
          value = Math.round(value);
        }

        weekly.push({
          day: days[i],
          value: value
        });
      }
      weeklyData.value = weekly;

      // 计算统计数据
      calculateStats(hourly, weekly);

      console.log('Generated hourly data:', hourlyData.value);
      console.log('Generated weekly data:', weeklyData.value);
    };

    const calculateStats = (hourly, weekly) => {
      const hourlyValues = hourly.map(item => item.value);
      const weeklyValues = weekly.map(item => item.value);

      stats.value = {
        todayMax: props.sensorType === 'ph' ?
          Math.max(...hourlyValues).toFixed(1) : Math.max(...hourlyValues),
        todayMin: props.sensorType === 'ph' ?
          Math.min(...hourlyValues).toFixed(1) : Math.min(...hourlyValues),
        todayAvg: props.sensorType === 'ph' ?
          (hourlyValues.reduce((a, b) => a + b, 0) / hourlyValues.length).toFixed(1) :
          Math.round(hourlyValues.reduce((a, b) => a + b, 0) / hourlyValues.length),
        weeklyMax: props.sensorType === 'ph' ?
          Math.max(...weeklyValues).toFixed(1) : Math.max(...weeklyValues),
        weeklyMin: props.sensorType === 'ph' ?
          Math.min(...weeklyValues).toFixed(1) : Math.min(...weeklyValues)
      };

      console.log('Calculated stats:', stats.value);
    };

    const closeModal = () => {
      emit('close');
    };

    // 监听传感器类型和当前值的变化
    watch([() => props.sensorType, () => props.currentValue], () => {
      console.log('Sensor type or value changed:', props.sensorType, props.currentValue);
      generateMockData();
    }, { immediate: true });

    // 当组件显示时重新生成数据
    watch(() => props.visible, (newVal) => {
      if (newVal) {
        console.log('Modal visible, regenerating data');
        // 添加延迟确保DOM已经渲染
        setTimeout(() => {
          generateMockData();
        }, 100);
      }
    });

    return {
      title,
      unit,
      hourlyData,
      weeklyData,
      maxValue,
      maxWeeklyValue,
      stats,
      closeModal
    };
  }
};
</script>

<style scoped>
.sensor-detail-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background: rgba(0, 0, 0, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
  backdrop-filter: blur(5px);
}

.modal-content {
  background: linear-gradient(135deg, #001c24 0%, #003543 100%);
  border: 2px solid #00ffd9;
  border-radius: 8px;
  width: 95%;
  height: 90%;
  padding: 20px;
  box-shadow: 0 0 50px rgba(0, 255, 217, 0.3);
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid rgba(0, 255, 217, 0.3);
}

.modal-header h2 {
  color: #00ffd9;
  margin: 0;
  font-size: 24px;
  text-shadow: 0 0 10px rgba(0, 255, 217, 0.5);
}

.close-btn {
  background: rgba(255, 107, 107, 0.2);
  border: 1px solid #ff6b6b;
  color: #ff6b6b;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  font-size: 24px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.close-btn:hover {
  background: rgba(255, 107, 107, 0.4);
  box-shadow: 0 0 15px rgba(255, 107, 107, 0.5);
}

.chart-container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-rows: auto auto;
  gap: 20px;
  height: auto;
}

.chart-section {
  background: rgba(0, 28, 36, 0.6);
  border: 1px solid rgba(0, 255, 217, 0.2);
  border-radius: 6px;
  padding: 15px;
  min-height: 300px;
}

.chart-section h3 {
  color: #ffffff;
  margin: 0 0 15px 0;
  text-align: center;
  font-size: 16px;
}

.chart-wrapper {
  height: calc(100% - 40px);
}

.chart-placeholder {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.chart-title {
  color: #00ffd9;
  text-align: center;
  margin-bottom: 15px;
  font-size: 14px;
  font-weight: bold;
}

.chart-data {
  display: flex;
  justify-content: space-around;
  align-items: flex-end;
  height: 200px;
  padding: 15px;
  border: 1px solid rgba(0, 255, 217, 0.2);
  border-radius: 4px;
  background: rgba(0, 255, 217, 0.05);
}

.data-bar {
  display: flex;
  flex-direction: column;
  align-items: center;
  flex: 1;
  margin: 0 2px;
  min-width: 30px;
}

.bar {
  width: 20px;
  background: linear-gradient(to top, #00ffd9, #ff6b6b);
  border-radius: 2px 2px 0 0;
  min-height: 5px;
  transition: height 0.3s ease;
}

.time,
.value {
  color: #ffffff;
  font-size: 10px;
  margin-top: 5px;
  text-align: center;
  word-break: keep-all;
}

.value {
  color: #00ffd9;
  font-weight: bold;
  font-size: 11px;
}

.weekly .bar {
  width: 25px;
}

.weekly .data-bar {
  min-width: 35px;
}

/* 统计数据样式 */
.stats-section {
  grid-column: 1 / -1;
  background: rgba(0, 28, 36, 0.6);
  border: 1px solid rgba(0, 255, 217, 0.2);
  border-radius: 6px;
  padding: 15px;
}

.stats-section h3 {
  color: #ffffff;
  margin: 0 0 15px 0;
  text-align: center;
  font-size: 16px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 15px;
}

.stat-item {
  display: flex;
  align-items: center;
  background: rgba(0, 255, 217, 0.1);
  border: 1px solid rgba(0, 255, 217, 0.3);
  border-radius: 6px;
  padding: 12px;
  transition: all 0.3s ease;
}

.stat-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(0, 255, 217, 0.2);
}

.stat-icon {
  font-size: 24px;
  margin-right: 12px;
}

.stat-content {
  flex: 1;
}

.stat-label {
  color: #ffffff;
  font-size: 12px;
  margin-bottom: 4px;
  opacity: 0.8;
}

.stat-value {
  color: #00ffd9;
  font-size: 18px;
  font-weight: bold;
  text-shadow: 0 0 10px rgba(0, 255, 217, 0.5);
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .chart-container {
    grid-template-columns: 1fr;
  }

  .stats-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 768px) {
  .modal-content {
    width: 98%;
    height: 95%;
    padding: 10px;
  }

  .stats-grid {
    grid-template-columns: 1fr;
  }

  .chart-data {
    height: 150px;
    padding: 10px;
  }

  .bar {
    width: 15px;
  }

  .weekly .bar {
    width: 20px;
  }

  .time,
  .value {
    font-size: 9px;
  }
}
</style>